package com.tim.app.ui.activity.selected;

import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutCompat;
import android.text.Html;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.application.library.net.StringResponseCallback;
import com.application.library.runtime.event.EventListener;
import com.application.library.runtime.event.EventManager;
import com.application.library.widget.roundimg.RoundedImageView;
import com.application.library.widget.smarttab.SmartTabLayout;
import com.google.gson.Gson;
import com.tim.app.R;
import com.tim.app.RT;
import com.tim.app.constant.AppKey;
import com.tim.app.constant.EventTag;
import com.tim.app.server.api.API_Found;
import com.tim.app.server.api.API_Statistics;
import com.tim.app.server.api.API_User;
import com.tim.app.server.entry.ActionStateMsg;
import com.tim.app.server.entry.Topic;
import com.tim.app.server.logic.UserManager;
import com.tim.app.server.net.ServerAddressManager;
import com.tim.app.server.result.FollowResult;
import com.tim.app.server.result.RelateTopicResult;
import com.tim.app.server.result.ResponseResult;
import com.tim.app.server.result.TopicDetailResult;
import com.tim.app.share.CustomShareBoard;
import com.tim.app.ui.activity.BaseActivity;
import com.tim.app.ui.activity.SearchActivity;
import com.tim.app.ui.adapter.TabAdapter;
import com.tim.app.ui.fragment.selceted.ProblemListFragment;
import com.tim.app.util.BitmapLoader;
import com.tim.app.util.ToastUtil;
import com.tim.app.util.ViewGT;
import com.umeng.socialize.UMShareAPI;

import java.util.List;


/**
 * 话题详情页面
 */
public class TopicDetailActivity extends BaseActivity {

    public static final String TAG = "TopicDetailActivity";
    private ImageButton ibBack, ibMore;
    private RoundedImageView rivAvatar;
    private TextView tvFollow;
    private TextView tvTopicName;
    private TextView tvAgreeCount;
    private TextView tvTopicDesc;
    private LinearLayoutCompat llSubject;
    private ViewPager vpSuject;
    private TabAdapter pageAdapter;
    private SmartTabLayout tab_layout;
    private boolean isFromPush = false;
    private LinearLayout llRelateTopic;

    private Topic topic;

    public static void start(Context context, Topic topic, boolean isFromPush) {
        Intent intent = new Intent(context, TopicDetailActivity.class);
        intent.putExtra(AppKey.TOPIC, topic);
        intent.putExtra(AppKey.IS_FROM_PUSH, isFromPush);
        if (isFromPush) {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        context.startActivity(intent);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_topic_detail;
    }

    @Override
    public void initView() {
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        ibBack = (ImageButton) findViewById(R.id.ibBack);
        ibMore = (ImageButton) findViewById(R.id.ibMore);
        rivAvatar = (RoundedImageView) findViewById(R.id.rivAvatar);

        tvFollow = (TextView) findViewById(R.id.tvFollow);
        tvTopicName = (TextView) findViewById(R.id.tvTopicName);
        tvAgreeCount = (TextView) findViewById(R.id.tvAgreeCount);
        tvTopicDesc = (TextView) findViewById(R.id.tvTopicDesc);
        llRelateTopic = (LinearLayout) findViewById(R.id.llRelateTopic);
        llSubject = (LinearLayoutCompat) findViewById(R.id.llSubject);

        tab_layout = (SmartTabLayout) findViewById(R.id.tab_layout);
        vpSuject = (ViewPager) findViewById(R.id.vpSuject);

        topic = (Topic) getIntent().getSerializableExtra(AppKey.TOPIC);
        isFromPush = getIntent().getBooleanExtra(AppKey.IS_FROM_PUSH, false);

        ibBack.setOnClickListener(this);
        ibMore.setOnClickListener(this);
        tvFollow.setOnClickListener(this);

        pageAdapter = new TabAdapter(getSupportFragmentManager());
        pageAdapter.addFragment(ProblemListFragment.newInstance(AppKey.PROBLEM_TYPE_NEWEST, topic.getId(), true), getString(R.string.newestSubjectTitle));
        pageAdapter.addFragment(ProblemListFragment.newInstance(AppKey.PROBLEM_TYPE_HOT, topic.getId(), true), getString(R.string.hotSubjectTitle));
        vpSuject.setOffscreenPageLimit(2);
        vpSuject.setAdapter(pageAdapter);
        vpSuject.setCurrentItem(0);
        tab_layout.setViewPager(vpSuject);

        EventManager.ins().registListener(EventTag.ACCOUNT_UPDATE_INFO, eventListener);
        EventManager.ins().registListener(EventTag.DO_REPORT, eventListener);
        API_Statistics.ins().addDetailData(TAG, this, AppKey.TYPE_TOPIC, topic.getId());
    }

    @Override
    public void initData() {
        API_Found.ins().getTopicDetail(TAG, topic.getId(), detailCallback);
        UserManager.ins().addBrowserHistory(TAG, AppKey.TYPE_TOPIC, topic.getId());
    }

    StringResponseCallback detailCallback = new StringResponseCallback() {
        @Override
        public boolean onStringResponse(String resultValue, int errCode, String errMsg, int id, boolean formCache) {
            if (errCode == ResponseResult.ResultStatus.OK && null != resultValue) {
                TopicDetailResult result = new Gson().fromJson(resultValue, TopicDetailResult.class);
                if (null != result && null != result.getRes().getTopic()) {
                    updateUi(result.getRes().getTopic());
                    getRelateTopics(result.getRes().getTopic().getpIds());
                }
            }
            return false;
        }
    };

    EventListener eventListener = new EventListener() {
        @Override
        public void handleMessage(int what, int arg1, int arg2, Object dataobj) {
            switch (what) {
                case EventTag.DO_REPORT://举报
                    if (UserManager.ins().isLogin()) {
                        UserManager.ins().report(TAG, AppKey.TYPE_TOPIC, topic.getId());
                    } else {
                        ViewGT.gotoLoginActivity(TopicDetailActivity.this);
                    }
                    break;
                case EventTag.ACCOUNT_UPDATE_INFO:
                    initData();
                    break;
            }
        }
    };

    /**
     * 更新UI
     *
     * @param topic
     */
    private void updateUi(Topic topic) {
        if (null == topic) return;
        if (!TextUtils.isEmpty(topic.getImage())) {
            BitmapLoader.ins().loadImage(topic.getImage(), rivAvatar);
        }
        if (!TextUtils.isEmpty(topic.getTopicName())) {
            tvTopicName.setText(topic.getTopicName());
        }
        if (!TextUtils.isEmpty(topic.getTopicDesc())) {
            tvTopicDesc.setText(Html.fromHtml(topic.getTopicDesc()));
        }
        tvAgreeCount.setText(getString(R.string.tvTotalFollowNumber, String.valueOf(topic.getConcernCount())));
        if (null != topic.getActionStateMsg()) {
            if (null != topic.getActionStateMsg().getContentState()) {
                tvFollow.setSelected(true);
                tvFollow.setText(R.string.hasFollow);
            } else {
                tvFollow.setSelected(false);
                tvFollow.setText(R.string.unFollow);
            }
        }
    }

    /**
     * 获取相关话题
     *
     * @param ids
     */
    private void getRelateTopics(String ids) {
        API_Found.ins().getRelateTopics(TAG, ids, new StringResponseCallback() {
            @Override
            public boolean onStringResponse(String resultValue, int errCode, String errMsg, int id, boolean formCache) {
                if (errCode == ResponseResult.ResultStatus.OK && null != resultValue) {
                    RelateTopicResult result = new Gson().fromJson(resultValue, RelateTopicResult.class);
                    if (null != result && null != result.getRes().getArraylist() && result.getRes().getArraylist().size() > 0) {
                        showRelevantTopic(result.getRes().getArraylist());
                    } else {
                        llRelateTopic.setVisibility(View.GONE);
                    }
                } else {
                    llRelateTopic.setVisibility(View.GONE);
                }
                return false;
            }
        });
    }

    /**
     * 显示相关话题
     *
     * @param relevantTopic
     */
    private void showRelevantTopic(final List<Topic> relevantTopic) {
        if (null != relevantTopic) {
            for (int i = 0; i < relevantTopic.size(); i++) {
                final Topic data = relevantTopic.get(i);
                TextView textView = new TextView(this);
                textView.setText(data.getTopicName());
                textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 11);
                textView.setBackground(getResources().getDrawable(R.drawable.bg_shape_gray_round));
                textView.setTextColor(getResources().getColor(R.color.text_desc_color));
                textView.setPadding((int) RT.getDensity() * 9, (int) RT.getDensity() * 1, (int) RT.getDensity() * 9, (int) RT.getDensity() * 1);
                textView.setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        TopicDetailActivity.start(TopicDetailActivity.this, data, false);
                    }
                });
                llSubject.addView(textView);
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
    }


    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventManager.ins().removeListener(EventTag.ACCOUNT_UPDATE_INFO, eventListener);
        EventManager.ins().removeListener(EventTag.DO_REPORT, eventListener);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tvFollow:
                if (!UserManager.ins().isLogin()) {
                    ViewGT.gotoLoginActivity(this);
                    return;
                }
                followOrCancelFollow();
                break;
            case R.id.ibBack:
                onBackPressed();
                break;
            case R.id.ibMore:
                CustomShareBoard shareBoard = new CustomShareBoard(this, CustomShareBoard.ShareFrom.NORMAL);
                String targetUrl = "";
                String sinaDesc = "";
                String imageUrl  = ServerAddressManager.SHARE_DEFAULT_LOGO_URL;
                if (!TextUtils.isEmpty(topic.getImage())) {
                    imageUrl = topic.getImage();
                }
                String desc = "";
                if (!TextUtils.isEmpty(topic.getTitle())) {
                    desc = topic.getTitle();
                } else {
//                    desc = RT.getString(R.string.share_desc_info);
                }
                shareBoard.setShareInfo(topic.getTitle(), desc, sinaDesc, imageUrl, imageUrl, targetUrl);
                shareBoard.showPopup(false);
                break;
            case R.id.etSearch:
                SearchActivity.start(this, SearchActivity.SEARCH_ALL, "");
                break;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            onBackPressed();
        }
        return false;
    }

    @Override
    public void onBackPressed() {
        if (isFromPush) {
            ViewGT.gotoMainActivity(TopicDetailActivity.this);
        } else {
            super.onBackPressed();
        }
    }

    /**
     * 关注/取消关注
     */
    private void followOrCancelFollow() {
        tvFollow.setEnabled(false);
        if (null != topic.getActionStateMsg() && topic.getActionStateMsg().getContentState() != null) {
            int id = topic.getActionStateMsg().getContentState();
            API_User.ins().cancelFollow(TAG, id, UserManager.ins().getUserId(), topic.getId(), AppKey.TYPE_TOPIC, new StringResponseCallback() {
                @Override
                public boolean onStringResponse(String resultValue, int errCode, String errMsg, int id, boolean formCache) {
                    tvFollow.setEnabled(true);
                    if (errCode == ResponseResult.ResultStatus.OK && resultValue != null) {
                        tvFollow.setSelected(false);
                        tvFollow.setText(R.string.unFollow);
                        topic.getActionStateMsg().setContentState(null);
                        topic.setConcernCount(topic.getConcernCount() - 1);
                        tvAgreeCount.setText(getString(R.string.tvTotalFollowNumber, String.valueOf(topic.getConcernCount())));
                    } else {
                        ToastUtil.showToast(errMsg);
                    }
                    return false;
                }
            });
        } else {
            API_User.ins().addFollow(TAG, UserManager.ins().getUserId(), topic.getId(), AppKey.TYPE_TOPIC, new StringResponseCallback() {
                @Override
                public boolean onStringResponse(String resultValue, int errCode, String errMsg, int id, boolean formCache) {
                    tvFollow.setEnabled(true);
                    if (errCode == ResponseResult.ResultStatus.OK && resultValue != null) {
                        FollowResult result = new Gson().fromJson(resultValue, FollowResult.class);
                        if (null != result && null != result.getRes()) {
                            if (topic.getActionStateMsg() == null) {
                                topic.setActionStateMsg(new ActionStateMsg());
                            }
                            topic.getActionStateMsg().setContentState(result.getRes().getConcern().getId());
                            tvFollow.setSelected(true);
                            tvFollow.setText(R.string.hasFollow);
                            topic.setConcernCount(topic.getConcernCount() + 1);
                            tvAgreeCount.setText(getString(R.string.tvTotalFollowNumber, String.valueOf(topic.getConcernCount())));
                        }
                    } else {
                        ToastUtil.showToast(errMsg);
                    }
                    return false;
                }
            });
        }
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }


}
